import React, { memo, FC, ReactNode, useRef, useEffect } from 'react'
import { BackTopWrapper } from './style'

interface IProps {
  children?: ReactNode
}

const BackTop: FC<IProps> = () => {
  const backToBtn = useRef<HTMLAnchorElement>(null)
  function backTo() {
    window.scroll(0, 0)
  }
  useEffect(() => {
    const doc = document.documentElement || document.body || document
    document.addEventListener('scroll', () => {
      if (doc.scrollTop > 50) {
        if (backToBtn.current) {
          backToBtn.current.style.display = 'block'
        }
      } else {
        if (backToBtn.current) {
          backToBtn.current.style.display = 'none'
        }
      }
    })
    return () => {
      document.removeEventListener('scroll', () => {
        return
      })
    }
  }, [])
  return <BackTopWrapper ref={backToBtn} onClick={backTo}></BackTopWrapper>
}

export default memo(BackTop)
